Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

HashSet → Java HashSet

HashSet

Java HashSet

HashSets in Java

A HashSet is an unordered collection that stores unique elements. It implements the Set interface and uses a hashing technique for fast element storage and retrieval. Hashing refers to a mechanism where elements are mapped to unique bucket positions based on their internal hash codes. This allows for average constant time (O(1)) lookups, insertions, and deletions.

Characteristics of HashSets

Uniqueness: HashSets don't allow duplicate elements. If you try to add a duplicate, it's simply ignored. Unordered: Elements are not stored in any specific order. The order you see when iterating through the set might differ each time. Hashing: Hashing is used for fast access. Each element's hashCode() method is used to calculate a hash code, which determines its position in the internal hash table. Null Values: HashSets allow storing a single null element.

Declaring and Initializing HashSets

Import
HashSet import syntax import java.util.HashSet;
This line imports the HashSet class from the java.util package.
Declaration
Declaring syntax HashSet<DataType> mySet;
This declares a variable named mySet of type HashSet. The <DataType> placeholder specifies the type of elements the set will hold. For example, HashSet<String> for strings or HashSet<Integer> for integers.
Initialization Default constructor:
Creating new Hashset mySet = new HashSet<DataType>();
This creates an empty HashSet object.
Adding elements during creation (Java 7+):
Adding initial elements during creation HashSet<String> fruits = new HashSet<String>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange");
This creates a HashSet and adds initial elements while constructing it.

Common HashSet Methods:

add(element): Adds an element to the set. contains(element): Checks if the set contains a specific element. remove(element): Removes an element from the set (if it exists). isEmpty(): Checks if the set is empty. size(): Returns the number of elements in the set.

Examples of HashSets

1. Integers
Hashset simple example in java import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(35); numbers.add(20); // Duplicate won't be added for (int number : numbers) { System.out.println(number); } } }

Output

35 20 10
This code creates a HashSet named numbers that stores integer values. It then iterates through the set and prints each element. Notice that adding a duplicate element ("20" again) has no effect as HashSets don't allow duplicates.
2. Strings
Hashset example using string elements in java import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<String> names = new HashSet<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("Alice"); // Duplicate won't be added for (String name : names) { System.out.println(name); } } }

Output

Bob Alice Charlie
This code creates a HashSet named names that stores string values representing names. It iterates through the set and prints each name. Similar to integers, duplicate elements ("Alice" again) are not added to the set.
3. Doubles
Hashset example using double elements in java import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Double> prices = new HashSet<>(); prices.add(19.99); prices.add(24.50); prices.add(12.75); prices.add(19.99); // Duplicate won't be added for (double price : prices) { System.out.println(price); } } }

Output

24.5 19.99 12.75
This code creates a HashSet named prices that stores double values representing prices. It iterates through the set and prints each price. As with other data types, duplicates are not allowed.
4. Characters
Hashset example using char elements in java import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Character> initials = new HashSet<>(); initials.add('A'); initials.add('B'); initials.add('C'); initials.add('A'); // Duplicate won't be added for (char initial : initials) { System.out.println(initial); } } }

Output

A B C
This code creates a HashSet named initials that stores character values representing initials. It iterates through the set and prints each character. Again, duplicate elements ("A" again) are not added.
5. Custom Objects
Hashset with objects as elements in java import java.util.HashSet; class Product { int id; String name; double price; public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } @Override public int hashCode() { return id; // Override hashCode() for proper object comparison within the HashSet } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Product other = (Product) obj; return id == other.id; // Override equals() to compare objects based on id } } public class Main { public static void main(String[] args) { HashSet<Product> products = new HashSet<>(); products.add(new Product(1, "Laptop", 599.99)); products.add(new Product(2, "Headphones", 79.95)); products.add(new Product(3, "Mobile", 279.95)); products.add(new Product(1, "Laptop", 499.99)); // Duplicate object (based on id) for (Product product : products) { System.out.println("ID: " + product.id + ", Name: " + product.name + ", Price: $" + product.price); } } }

Output

ID: 1, Name: Laptop, Price: $599.99 ID: 2, Name: Headphones, Price: $79.95 ID: 3, Name: Mobile, Price: $279.95
This code defines a custom class Product with attributes like id, name, and price. It then creates a HashSet named products that stores instances of the Product class. However, for HashSets to work correctly with custom objects, you need to override the hashCode() and equals() methods of your class to define how objects are compared for uniqueness within the set. In this example, the hashCode() and equals() methods are overridden to compare objects based on their id property. The code adds a duplicate product with the same id (1, "Laptop", 499.99), but only one instance will be present in the set.
In Conclusion: HashSets are a powerful tool for storing unique elements and offer efficient lookups, insertions, and deletions. They are a good choice when you need a collection where order doesn't matter, and fast access by element is crucial. However, if you need to maintain insertion order, consider using a LinkedHashSet.

Tutorials